/** 图片和txt文件由于同源策略，无法直接下载
 *
*/

/**
    * 文件下载
    * 根据文件的后缀判断文件类型，
    * excel类型的文件可以直接下载，
    * txt文件需要先下载都到本地，转换为blob，下载
    * @param {url} 文件url地址
    * @param {name} 文件名字
    */
export function downloadFile (url, name) {
  const txtArr = ['txt', 'json']
  const suffix = getSuffix(name)
  if (txtArr.includes(suffix)) {
    var oReq = new XMLHttpRequest()
    oReq.addEventListener('load', (e) => {
      const blob = new Blob([e.currentTarget.response])
      const newUrl = URL.createObjectURL(blob)
      aTagDownload(newUrl, name)
    })
    oReq.open('GET', url)
    oReq.responseType = 'arraybuffer'
    oReq.send()
  } else {
    aTagDownload(url, name)
  }
}

/**
    * 创建a标签下载文件
    * @param {newUrl}
    * @param {name} 文件名字
    */
function aTagDownload (newUrl, name) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement('a')
  eleLink.href = newUrl
  eleLink.download = name
  eleLink.style.display = 'none'
  document.body.appendChild(eleLink)
  eleLink.click()
  document.body.removeChild(eleLink)
}

/**
    * 图片下载
    * @param {url} 图片url地址
    * @param {name} 文件名字
    */
export function downloadImage (url, name) {
  const image = new Image()
  image.src = url
  image.setAttribute('crossOrigin', 'Anonymous')
  image.onload = function (res) {
    const base64 = getBase64Image(image)
    const blob = dataURLtoBlob(base64)
    const newUrl = URL.createObjectURL(blob)
    aTagDownload(newUrl, name)
  }
}

/**
    * 图像转Base64
    */
export function getBase64Image (img) {
  var canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  var ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, img.width, img.height)
  var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
  var dataURL = canvas.toDataURL('image/' + ext)
  return dataURL
}

/**
 *Base64字符串转二进制
*/
export function dataURLtoBlob (dataurl) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {
    type: mime
  })
}

/**
 * 根据文件名称，获得文件的后缀
*/
function getSuffix (name) {
  var index = name.lastIndexOf('.')
  return name.substr(index + 1)
}
